package readsourcecode.ch2;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Date 2022/8/8
 * @Author Jonathan
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    public static void autowiredBean(Object instance) {
        applicationContext.getAutowireCapableBeanFactory().autowireBean(instance);
    }

    public static Object getBeanByName(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBeanOfType(Class<T> type) {
        List<T> ans = getBeansOfType(type);
        if (CollectionUtils.isEmpty(ans)) {
            return null;
        }
        return ans.get(0);
    }


    public static <T> List<T> getBeansOfType(Class<T> type) {
        List<T> ans = new ArrayList<>();
        final Map<String, T> m = applicationContext.getBeansOfType(type);
        for (Map.Entry<String, T> b : m.entrySet()) {
            ans.add(b.getValue());
        }
        return ans;
    }

    public static List<String> getBeanNamesForType(Class type) {
        final String[] beanNamesForType = applicationContext.getBeanNamesForType(type);
        return Arrays.asList(beanNamesForType);
    }


}
